package com.gistmap.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gistmap.dto.*;
import com.gistmap.service.ActivityService;
import com.gistmap.service.ArticleService;
import com.gistmap.util.Pager;
import com.gistmap.util.Result;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.gistmap.bean.User;
import com.gistmap.service.UserService;
import com.gistmap.util.Constant;

@Controller
@RequestMapping("/user")
public class UserController
{
	@Autowired
	private UserService userService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ActivityService activityService;

	@RequestMapping("/register")
	public ModelAndView register(User user)
	{
		ModelAndView mv = new ModelAndView("tips");
		int i = userService.register(user);
		if (i == 1)
			mv.addObject("tip", Constant.REGISTER_SUCCESS);
		else
			mv.addObject("tip", Constant.REGISTER_ERROR);

		return mv;
	}

	@RequestMapping("/nameRepeat")
	public void nameRepeat(String username, HttpServletResponse response) throws IOException
	{
		String result = "";

		result = "" + userService.nameRepeat(username);

		response.getWriter().write(result);
	}

	@RequestMapping("/login")
	public void login(User user, HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String result = "";
		User temp = userService.getByUserName(user.getUsername());
		if (temp == null)
		{
			result = Constant.USER_NOT_EXIST;
		}
		else
		{
			if (user.getPwd().equals(temp.getPwd()))
			{
				System.out.println(temp.getId());
				result = Constant.SUCCESS;
				request.getSession().setAttribute("user", temp);

			}
			else
			{
				result = Constant.PWD_ERROR;
			}
		}

		response.getWriter().write(result);
	}

	@RequestMapping("/logout")
	public String Logout(HttpServletRequest request)
	{
		HttpSession session = request.getSession(false);// 防止创建Session
		if (session == null)
		{
			return "login";
		}
		session.removeAttribute("user");
		return "login";
	}

	@RequestMapping("/upload")
	@ResponseBody
	public Result upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,HttpSession httpSession)
	{
		String message = "";
		boolean success = true;
		User user = (User) httpSession.getAttribute("user");
		int uid = user.getId();
		String path = request.getSession().getServletContext().getRealPath("/")+"/res/userImg/";
		String fileName = file.getOriginalFilename();
		System.out.println("************************"+path);

		if (fileName != null && !"".equals(fileName.trim()))
		{
			long size = file.getSize();
			if (size > 1024*1024)
			{
				message = "只允许上传1M以内大小的图片";
				success = false;
				return new Result(success,message);
			}

			else
			{
				File targetFile = new File(path,fileName);

				try {
					file.transferTo(targetFile);
				} catch (IOException e) {
					e.printStackTrace();
				}
				userService.saveAvatar(fileName,uid);
				message=request.getContextPath()+"/res/userImg/"+fileName;
				System.out.println("#######################"+message);
				//刷新操作

				//end
				success = true;
				User temp = (User)request.getSession().getAttribute("user");
				User update = userService.getByUserName(temp.getUsername());
				request.getSession().setAttribute("user",update);
				return new Result(success,message);
			}
		}
		else
		{
			message = "文件名无效";
			success = false;
			return new Result(success,message);
		}

	}

	@RequestMapping("/editUser")
	public ModelAndView editUser(Integer uid)
	{
		ModelAndView mv = new ModelAndView("settings");
		User editUser = userService.getById(uid);
		mv.addObject("editUser",editUser);

		return mv;
	}

	@RequestMapping("/update")
	public String updateUser(User user,HttpServletRequest request,Model model)
	{
		User getUser = (User) request.getSession().getAttribute("user");
		user.setId(getUser.getId());
		userService.update(user);

		User temp = (User)request.getSession().getAttribute("user");
		User update = userService.getByUserName(temp.getUsername());
		request.getSession().setAttribute("user",update);
		model.addAttribute("tip","7");
		return "tips";
	}

	@RequestMapping("/visitUser")
	public ModelAndView visitUser(Integer uid,HttpServletRequest request)
	{
		User current = (User)request.getSession().getAttribute("user");
		ModelAndView mv = new ModelAndView("visitUserPage");
		//被访问的用户信息
		User user = userService.getById(uid);

		Pager pager = null;
		int pageSize = 5;
		int pageNo = 0;

		String pageNoStr = request.getParameter("pageNo");
		System.out.println(pageNoStr);
		if (null == pageNoStr)
			pageNo = 1;
		else
			pageNo = Integer.parseInt(pageNoStr);

		Map<String,Object> params  =  new HashedMap();
		params.put("index", pageNo);
		params.put("pageSize", pageSize);
		params.put("uid",uid);
		//被访问的用户文章
		pager = articleService.getByPage(params);
		//被访问的用户活动
		List<ActivityDto> list = activityService.showVisit(uid);

		//活动参与的状态
		List<Integer> joinList = activityService.getJoinInfo(current.getId());
		JSONArray jsonArray = JSONArray.fromObject(joinList);
		String status = jsonArray.toString();
		//用户关注状态
		List<Integer> focusStatusList = userService.curFocusStatus(current.getId());
		JSONArray jsonArr = JSONArray.fromObject(focusStatusList);
		String focusStatus = jsonArr.toString();

		Integer care = userService.getCareCount(uid);
		Integer fans = userService.getFansCount(uid);
		Integer arts = articleService.getArtCount(uid);

		//1.被访问的用户信息
		mv.addObject("visitUserInfo",user);
		//2.被访问的用户文章
		mv.addObject("visitArtPager",pager);
		//3.被访问的用户活动
		mv.addObject("visitAct",list);
		//4.活动参与的状态
		mv.addObject("currentActStatus",status);
		//5.用户关注状态
		mv.addObject("focusStatus",focusStatus);
		//6.用户卡片数据
		mv.addObject("care",care);
		mv.addObject("fans",fans);
		mv.addObject("arts",arts);
		return mv;
	}
	/*
		添加关注（建立好友关系，触发被添加人，记录事件）
	 */
	@RequestMapping("/takeCare")
	public void takeCare(Integer curId,Integer careId,HttpServletResponse response) throws IOException {
		String result = "";
		try{

			Map<String,Object> params = new HashedMap();
			params.put("opt",1);
			params.put("oid",curId);
			params.put("bid",careId);
			params.put("source",null);
			userService.saveFriend(curId,careId,params);
			result = "1";

		}
		catch (Exception e)
		{
			result = "0";
		}
		System.out.println(result);
		response.getWriter().write(result);

	}


	@RequestMapping("/closeCare")
	public void closeCare(Integer curId,Integer careId,HttpServletResponse response) throws IOException {
		String result = "";

		try{

			Map<String,Object> params = new HashedMap();
			params.put("opt",2);
			params.put("oid",curId);
			params.put("bid",careId);
			params.put("source",null);
			userService.closeFriend(curId,careId,params);
			result = "1";

		}
		catch (Exception e)
		{
			result = "0";
		}
		System.out.println(result);
		response.getWriter().write(result);

	}

	@RequestMapping("relatedToMe")
	public ModelAndView relatedToMe(HttpServletRequest request)
	{
		ModelAndView mv = new ModelAndView("relatedTo");
		User current = (User)request.getSession().getAttribute("user");

		List<MessageDto> list = userService.getRelated(current.getId());

		mv.addObject("MessageList",list);
		return mv;
	}

	@RequestMapping("/closeMessage")
	public void closeMessage(HttpServletRequest request)
	{
		User current = (User)request.getSession().getAttribute("user");

		try {
			userService.closeMessage(current.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		User temp = (User)request.getSession().getAttribute("user");
		User user = userService.getByUserName(temp.getUsername());
		request.getSession().setAttribute("user",user);
	}

	@RequestMapping("/getCardInfo")
	public void getCardInfo(int uid,HttpServletResponse response) throws IOException {
		List<Integer> cardInfo = new ArrayList<Integer>();
		Integer care = userService.getCareCount(uid);
		Integer fans = userService.getFansCount(uid);
		Integer arts = articleService.getArtCount(uid);

		if(care != null)
		{
			cardInfo.add(care);
		}
		else
		{
			cardInfo.add(0);
		}
		if(fans != null)
		{
			cardInfo.add(fans);
		}
		else
		{
			cardInfo.add(0);
		}
		if(arts != null)
		{
			cardInfo.add(arts);
		}
		else
		{
			cardInfo.add(0);
		}

		JSONArray jsonArray = JSONArray.fromObject(cardInfo);
		System.out.println(jsonArray);
		String result = jsonArray.toString();
		response.getWriter().write(result);
	}

	@RequestMapping("/showfriends")
	public ModelAndView showFriends(Integer uid)
	{
		ModelAndView mv = new ModelAndView("myfriend");
		List<Friend> clist = userService.getFriend(uid);
		List<Friend> flist = userService.getFans(uid);
		System.out.println(flist);
		mv.addObject("flist",flist);
		mv.addObject("clist",clist);

		List<Integer> careList = userService.curFocusStatus(uid);
		List<Integer> fansList = userService.curFocusMeStatus(uid);

		fansList.removeAll(careList);
		mv.addObject("fansList",fansList);
		careList.removeAll(fansList);
		mv.addObject("careList",careList);

		System.out.println("carelist"+careList);
		System.out.println("fanslist"+fansList);
		return mv;
	}
}
